Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources

In [0]:
# TODO: Make all necessary imports.

import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import time
import numpy as np
import matplotlib.pyplot as plt

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
tfds.disable_progress_bar()
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
In [2]:
%pip --no-cache-dir install tfds-nightly
Collecting tfds-nightly
  Downloading https://files.pythonhosted.org/packages/4c/6a/dfaea45658248d8ded5eb8d260a193ff8179d64ac993c5e5a26dc5a87fd3/tfds_nightly-3.1.0.dev202005030105-py3-none-any.whl (3.3MB)
     |████████████████████████████████| 3.3MB 4.9MB/s 
Requirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (2.3)
Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (2.23.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (4.38.0)
Requirement already satisfied: wrapt in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (1.12.1)
Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (1.18.3)
Requirement already satisfied: termcolor in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (1.12.0)
Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (0.16.0)
Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (3.10.0)
Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (19.3.0)
Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (0.3.1.1)
Requirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (0.9.0)
Collecting tensorflow-metadata<0.16,>=0.15
  Downloading https://files.pythonhosted.org/packages/3b/0c/afb81ea6998f6e26521671585d1cd9d3f7945a8b9834764e91757453dc25/tensorflow_metadata-0.15.2-py2.py3-none-any.whl
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly) (2020.4.5.1)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly) (1.24.3)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly) (2.9)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.6.1->tfds-nightly) (46.1.3)
Requirement already satisfied: googleapis-common-protos in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata<0.16,>=0.15->tfds-nightly) (1.51.0)
Installing collected packages: tensorflow-metadata, tfds-nightly
  Found existing installation: tensorflow-metadata 0.21.2
    Uninstalling tensorflow-metadata-0.21.2:
      Successfully uninstalled tensorflow-metadata-0.21.2
Successfully installed tensorflow-metadata-0.15.2 tfds-nightly-3.1.0.dev202005030105

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [3]:
# TODO: Load the dataset with TensorFlow Datasets.
dataset, dataset_info = tfds.load('oxford_flowers102', with_info=True, as_supervised=True)
# TODO: Create a training set, a validation set and a test set.
test_set, training_set, validation_set = dataset['test'], dataset['train'], dataset['validation']
Downloading and preparing dataset oxford_flowers102/2.0.0 (download: 336.76 MiB, generated: Unknown size, total: 336.76 MiB) to /root/tensorflow_datasets/oxford_flowers102/2.0.0...
Shuffling and writing examples to /root/tensorflow_datasets/oxford_flowers102/2.0.0.incomplete8PN8NJ/oxford_flowers102-train.tfrecord
Shuffling and writing examples to /root/tensorflow_datasets/oxford_flowers102/2.0.0.incomplete8PN8NJ/oxford_flowers102-test.tfrecord
Shuffling and writing examples to /root/tensorflow_datasets/oxford_flowers102/2.0.0.incomplete8PN8NJ/oxford_flowers102-validation.tfrecord
Dataset oxford_flowers102 downloaded and prepared to /root/tensorflow_datasets/oxford_flowers102/2.0.0. Subsequent calls will reuse this data.

Explore the Dataset

In [11]:
# TODO: Get the number of examples in each set from the dataset info.
num_training_examples  = dataset_info.splits['train'].num_examples
num_test_examples  = dataset_info.splits['test'].num_examples
num_validation_examples  = dataset_info.splits['validation'].num_examples

print('Number of training examples: {}'.format(num_training_examples))
print('Number of test examples: {}'.format(num_test_examples))
print('Number of validation examples: {}'.format(num_validation_examples))

# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes
print('Number of classes: {}'.format(num_classes))
Number of training examples: 1020
Number of test examples: 6149
Number of validation examples: 1020
Number of classes: 102
In [12]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in training_set.take(3):
  print('Image label: {}, Image shape: {}'.format(label, image.shape))
Image label: 72, Image shape: (500, 667, 3)
Image label: 84, Image shape: (500, 666, 3)
Image label: 70, Image shape: (670, 500, 3)
In [13]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding image label. 

for image, label in training_set.take(1):
    image = image.numpy().squeeze()
    label = label.numpy()

plt.figure()
plt.imshow(image, cmap=plt.cm.binary)
plt.title('Label: {}'.format(label))
plt.colorbar()
plt.grid(False)
plt.show()

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [0]:
import json

with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [15]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 

plt.figure()
plt.imshow(image, cmap=plt.cm.binary)
plt.title('Label: {}'.format( class_names[str(label+1)]))
plt.colorbar()
plt.grid(False)
plt.show()

Create Pipeline

In [16]:
# TODO: Create a pipeline for each set.

batch_size = 32
image_size = 224

def format_image(image, label):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (image_size, image_size))
    image /= 255
    return image, label

training_batches = training_set.cache().shuffle(num_training_examples//4).map(format_image).batch(batch_size).prefetch(1)
testing_batches = test_set.cache().map(format_image).batch(batch_size).prefetch(1)
validation_batches = validation_set.map(format_image).batch(batch_size).prefetch(1)

for image, label in training_batches.take(1):
  plt.figure()
  plt.imshow(image[0].numpy().squeeze(), cmap=plt.cm.binary)
  plt.colorbar()
  plt.grid(False)
  plt.show()

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [17]:
# TODO: Build and train your network.

URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"

feature_extractor = hub.KerasLayer(URL, input_shape=(image_size, image_size,3))

feature_extractor.trainable = False

model = tf.keras.Sequential([
        feature_extractor,
        tf.keras.layers.Dense(num_classes, activation = 'softmax')
])

model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dense (Dense)                (None, 102)               130662    
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________
In [18]:
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
EPOCHS = 35
# Stop training when there is no improvement in the validation loss for 5 consecutive epochs
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)

history = model.fit(training_batches,
                    epochs = EPOCHS,
                    validation_data=validation_batches,
                    callbacks=[early_stopping])
Epoch 1/35
32/32 [==============================] - 8s 260ms/step - loss: 4.2718 - accuracy: 0.1029 - val_loss: 3.0647 - val_accuracy: 0.3755
Epoch 2/35
32/32 [==============================] - 7s 204ms/step - loss: 2.0780 - accuracy: 0.6784 - val_loss: 1.9769 - val_accuracy: 0.6676
Epoch 3/35
32/32 [==============================] - 7s 205ms/step - loss: 1.1032 - accuracy: 0.8980 - val_loss: 1.5122 - val_accuracy: 0.7422
Epoch 4/35
32/32 [==============================] - 7s 205ms/step - loss: 0.6761 - accuracy: 0.9647 - val_loss: 1.2734 - val_accuracy: 0.7716
Epoch 5/35
32/32 [==============================] - 7s 206ms/step - loss: 0.4480 - accuracy: 0.9833 - val_loss: 1.1374 - val_accuracy: 0.7833
Epoch 6/35
32/32 [==============================] - 7s 206ms/step - loss: 0.3187 - accuracy: 0.9902 - val_loss: 1.0471 - val_accuracy: 0.8000
Epoch 7/35
32/32 [==============================] - 6s 203ms/step - loss: 0.2391 - accuracy: 0.9971 - val_loss: 0.9858 - val_accuracy: 0.8049
Epoch 8/35
32/32 [==============================] - 7s 206ms/step - loss: 0.1846 - accuracy: 0.9990 - val_loss: 0.9360 - val_accuracy: 0.8069
Epoch 9/35
32/32 [==============================] - 7s 207ms/step - loss: 0.1482 - accuracy: 0.9990 - val_loss: 0.9060 - val_accuracy: 0.8059
Epoch 10/35
32/32 [==============================] - 7s 207ms/step - loss: 0.1209 - accuracy: 1.0000 - val_loss: 0.8761 - val_accuracy: 0.8088
Epoch 11/35
32/32 [==============================] - 7s 209ms/step - loss: 0.1014 - accuracy: 1.0000 - val_loss: 0.8551 - val_accuracy: 0.8118
Epoch 12/35
32/32 [==============================] - 7s 207ms/step - loss: 0.0861 - accuracy: 1.0000 - val_loss: 0.8338 - val_accuracy: 0.8167
Epoch 13/35
32/32 [==============================] - 7s 206ms/step - loss: 0.0744 - accuracy: 1.0000 - val_loss: 0.8201 - val_accuracy: 0.8118
Epoch 14/35
32/32 [==============================] - 7s 207ms/step - loss: 0.0651 - accuracy: 1.0000 - val_loss: 0.8051 - val_accuracy: 0.8147
Epoch 15/35
32/32 [==============================] - 7s 206ms/step - loss: 0.0576 - accuracy: 1.0000 - val_loss: 0.7938 - val_accuracy: 0.8176
Epoch 16/35
32/32 [==============================] - 7s 206ms/step - loss: 0.0514 - accuracy: 1.0000 - val_loss: 0.7843 - val_accuracy: 0.8137
Epoch 17/35
32/32 [==============================] - 7s 206ms/step - loss: 0.0460 - accuracy: 1.0000 - val_loss: 0.7740 - val_accuracy: 0.8176
Epoch 18/35
32/32 [==============================] - 7s 206ms/step - loss: 0.0416 - accuracy: 1.0000 - val_loss: 0.7655 - val_accuracy: 0.8196
Epoch 19/35
32/32 [==============================] - 7s 204ms/step - loss: 0.0380 - accuracy: 1.0000 - val_loss: 0.7586 - val_accuracy: 0.8157
Epoch 20/35
32/32 [==============================] - 7s 205ms/step - loss: 0.0347 - accuracy: 1.0000 - val_loss: 0.7509 - val_accuracy: 0.8157
Epoch 21/35
32/32 [==============================] - 7s 206ms/step - loss: 0.0319 - accuracy: 1.0000 - val_loss: 0.7458 - val_accuracy: 0.8157
Epoch 22/35
32/32 [==============================] - 6s 202ms/step - loss: 0.0294 - accuracy: 1.0000 - val_loss: 0.7407 - val_accuracy: 0.8206
Epoch 23/35
32/32 [==============================] - 7s 205ms/step - loss: 0.0273 - accuracy: 1.0000 - val_loss: 0.7340 - val_accuracy: 0.8186
Epoch 24/35
32/32 [==============================] - 7s 206ms/step - loss: 0.0253 - accuracy: 1.0000 - val_loss: 0.7302 - val_accuracy: 0.8176
Epoch 25/35
32/32 [==============================] - 7s 208ms/step - loss: 0.0236 - accuracy: 1.0000 - val_loss: 0.7253 - val_accuracy: 0.8186
Epoch 26/35
32/32 [==============================] - 7s 208ms/step - loss: 0.0221 - accuracy: 1.0000 - val_loss: 0.7222 - val_accuracy: 0.8176
Epoch 27/35
32/32 [==============================] - 7s 208ms/step - loss: 0.0207 - accuracy: 1.0000 - val_loss: 0.7182 - val_accuracy: 0.8176
Epoch 28/35
32/32 [==============================] - 7s 204ms/step - loss: 0.0195 - accuracy: 1.0000 - val_loss: 0.7135 - val_accuracy: 0.8206
Epoch 29/35
32/32 [==============================] - 7s 206ms/step - loss: 0.0183 - accuracy: 1.0000 - val_loss: 0.7112 - val_accuracy: 0.8176
Epoch 30/35
32/32 [==============================] - 7s 205ms/step - loss: 0.0173 - accuracy: 1.0000 - val_loss: 0.7086 - val_accuracy: 0.8167
Epoch 31/35
32/32 [==============================] - 7s 208ms/step - loss: 0.0164 - accuracy: 1.0000 - val_loss: 0.7051 - val_accuracy: 0.8176
Epoch 32/35
32/32 [==============================] - 7s 204ms/step - loss: 0.0155 - accuracy: 1.0000 - val_loss: 0.7032 - val_accuracy: 0.8176
Epoch 33/35
32/32 [==============================] - 7s 205ms/step - loss: 0.0147 - accuracy: 1.0000 - val_loss: 0.6997 - val_accuracy: 0.8235
Epoch 34/35
32/32 [==============================] - 7s 208ms/step - loss: 0.0140 - accuracy: 1.0000 - val_loss: 0.6972 - val_accuracy: 0.8186
Epoch 35/35
32/32 [==============================] - 7s 207ms/step - loss: 0.0133 - accuracy: 1.0000 - val_loss: 0.6951 - val_accuracy: 0.8206
In [20]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.

training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range = range(EPOCHS)

plt.figure()
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [21]:
# Testing on some image sample from testing batch
for image_batch, label_batch in testing_batches.take(1):
    ps = model.predict(image_batch)
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()

plt.figure(figsize=(10,15))

for n in range(30):
    plt.subplot(6,5,n+1)
    plt.imshow(images[n], cmap = plt.cm.binary)
    color = 'green' if np.argmax(ps[n]) == labels[n] else 'red'
    plt.title(class_names[str(np.argmax(ps[n])+1)], color=color)
    plt.axis('off')
In [22]:
# TODO: Print the loss and accuracy values achieved on the entire test set.

results = model.evaluate(testing_batches)
print('test loss: {}, test acc: {}'.format(results[0], results[1]))
193/193 [==============================] - 26s 135ms/step - loss: 0.8383 - accuracy: 0.7861
test loss: 0.8383316993713379, test acc: 0.7861440777778625

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [0]:
# TODO: Save your trained model as a Keras model.

saved_keras_model_filepath = './{}.h5'.format('saved_model_1')

model.save(saved_keras_model_filepath)

Load the Keras Model

Load the Keras model you saved above.

In [24]:
# TODO: Load the Keras model

reloaded_keras_model = tf.keras.models.load_model(saved_keras_model_filepath, custom_objects={'KerasLayer': hub.KerasLayer})
reloaded_keras_model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dense (Dense)                (None, 102)               130662    
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [0]:
# TODO: Create the process_image function

def process_image(img):
    image = np.squeeze(img)
    image = tf.image.resize(image, (image_size, image_size))
    image = image/255.0
    return image.numpy()

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [26]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [0]:
# TODO: Create the predict function

def predict(image_path, model_pred, top_k = 2):
  image_path = image_path
  im = Image.open(image_path)
  test_image = np.asarray(im)
  processed_test_image = process_image(test_image)

  ps = model_pred.predict(np.expand_dims(processed_test_image, axis=0))
  # images = image_batch.numpy().squeeze()
  # labels = label_batch.numpy()
  # print('test loss, test acc:', labels)

  top_values, top_indices = tf.math.top_k(ps, top_k)
  print("These are the top propabilities",top_values.numpy()[0])
  top_classes = [class_names[str(value+1)] for value in top_indices.cpu().numpy()[0]]
  print('Of these top classes', top_classes)
  return top_values.numpy()[0], top_classes

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [28]:
# TODO: Plot the input image along with the top 5 classes

files =['cautleya_spicata.jpg', 'hard-leaved_pocket_orchid.jpg', 'orange_dahlia.jpg', 'wild_pansy.jpg']
base_path = './test_images/'
for image_path in files:
    image_path = base_path+image_path
    im = Image.open(image_path)
    test_image = np.asarray(im)
    processed_test_image = process_image(test_image)
    probs, classes = predict(image_path, reloaded_keras_model, 5)
    fig, (ax1, ax2) = plt.subplots(figsize=(12,4), ncols=2)
    ax1.imshow(processed_test_image)
    ax2 = plt.barh(classes[::-1], probs[::-1])
    plt.tight_layout()
    plt.show()
These are the top propabilities [0.9755854  0.00837567 0.00517067 0.00183689 0.00152689]
Of these top classes ['cautleya spicata', 'wallflower', 'red ginger', 'siam tulip', 'snapdragon']
These are the top propabilities [9.9935430e-01 1.1519687e-04 1.1142203e-04 9.1235095e-05 5.9051989e-05]
Of these top classes ['hard-leaved pocket orchid', 'moon orchid', 'anthurium', 'passion flower', 'tiger lily']
These are the top propabilities [0.3962512  0.39141306 0.04640574 0.03356562 0.03145514]
Of these top classes ['orange dahlia', 'english marigold', 'blanket flower', 'osteospermum', 'bishop of llandaff']
These are the top propabilities [9.9748260e-01 6.8334007e-04 6.7194656e-04 2.4588726e-04 1.5378017e-04]
Of these top classes ['wild pansy', 'silverbush', 'balloon flower', 'mexican aster', 'buttercup']
In [0]: